package com.chengww.grab_rp.base

import android.os.Bundle
import android.view.View
import androidx.annotation.LayoutRes
import androidx.annotation.StringRes
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import com.chengww.grab_rp.BR
import com.chengww.grab_rp.utils.ToastUtil

/**
 * Created by chengww on 2/19/21
 * @author chengww
 */
abstract class BaseActivity<VM : BaseViewModel, VB : ViewDataBinding> : AppCompatActivity(),
    View.OnClickListener {
    val loading: LoadingDialog by lazy { LoadingDialog(this) }

    lateinit var vm: VM

    val v: VB by lazy { DataBindingUtil.setContentView(this, layoutId()) }

    @LayoutRes
    abstract fun layoutId(): Int

    abstract fun provideVM(): VM

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        vm = provideVM()
        v.setVariable(BR.vm, vm)
        v.executePendingBindings()
        v.lifecycleOwner = this
        vm.loading.observe(this) {
            if (it) loading.show() else loading.dismiss()
        }

        vm.error.observe(this) {
            if (it.isNullOrEmpty()) return@observe
            toast(it)
        }

        initView()
    }

    abstract fun initView()

    fun toast(message: CharSequence) = ToastUtil.show(this, message)

    fun toast(@StringRes message: Int) = ToastUtil.show(this, getString(message))

    override fun onClick(view: View) {

    }
}